package com.bsu.presentation.action;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import com.bsu.bean.Blog;
import com.bsu.bean.User;
import com.bsu.database.dao.UserDAO;
import com.bsu.presentation.form.BlogForm;
import com.bsu.presentation.form.UserForm;

public class UserAction extends DispatchAction{
	private UserDAO userDao = new UserDAO();
	public ActionForward login(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception{
			UserForm usf = (UserForm) form;
			User user = new User();
			user.setLogin(usf.getLogin());
			user.setPassword(usf.getPassword());
			List<User> users = new ArrayList<User>();
			ActionForward fg;
			HttpSession session = request.getSession();
			try {
					users = userDao.getUser(user.getLogin(),user.getPassword());
					
					if(!users.isEmpty()){
						
						
						for(User us : users){
							user.setIdUser(us.getIdUser());
//							user.setLogin(us.getLogin());
//							user.setPassword(us.getPassword());
							
						}
						session.setAttribute("user", user);
						fg = mapping.findForward("login");
					}else {
						fg = mapping.findForward("error");
					}
					
			} catch (Exception e) {
				usf = (UserForm) form;
				return mapping.findForward("error");
			}
			return fg;
		
			
			
		}
				
	public ActionForward add(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception{
		UserForm usf = (UserForm) form;
		User user = new User();
		ActionForward fg = null;
		user.setLogin(usf.getLogin());
		user.setPassword(usf.getPassword());
		try{
			userDao.add(user);
			fg = mapping.findForward("index");
		}catch (Exception e) {
			fg = mapping.findForward("error");
		}		
		return fg;
	}
	
	public ActionForward signOut(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception{
		UserForm usf = null;
		User user = new User();
		ActionForward fg = null;
		HttpSession session = request.getSession();
		session.removeAttribute("user");
		try{
			fg = mapping.findForward("index");
		}catch (Exception e) {
			fg = mapping.findForward("error");
		}		
		return fg;
	}
	
}
